﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeRepositoryConsole.FCL
{
    class ByteArrayToStream
    {
        /// <summary>
        /// create MemoryStream by Write
        /// </summary>
        /// <param name="myByteArrary"></param>
        /// <see cref="https://stackoverflow.com/questions/4736155/how-do-i-convert-byte-to-stream-in-c"/>
        /// <returns></returns>
        public MemoryStream ToStreamByWrite(byte[] myByteArrary)
        {
            // remember to reset stream afterward: stream.Seek(0, SeekOrigin.Begin);

            MemoryStream stream = new MemoryStream();
            stream.Write(myByteArrary, 0, myByteArrary.Length);
            return stream;
        }

        /// <summary>
        /// create non-resizeable MemoryStream
        /// </summary>
        /// <param name="myByteArrary"></param>
        /// <see cref="https://msdn.microsoft.com/en-us/library/e55f3s5k.aspx"/>
        /// <see cref="https://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx"/>
        /// <returns></returns>
        public MemoryStream ToStreamByCtor(byte[] myByteArrary)
        {

            // 1. The new stream can be written to, but is not resizeable.
            // 2. The length of the stream cann't be set to a value greater than the initial length of
            // the specified byte array; however, the stream can be truncated
            // 3. The constructor does not expose the underlying stream. GetBuffer throw UnauthorizedAccessException.
            MemoryStream stream = new MemoryStream(myByteArrary);
            return stream;
        }

    }
}
